<?php
$name = pods_url_variable('name', 'get');//Pod Name
$items = pods_url_variable('items', 'get');//Number of items, -1 for all
$sort = pods_url_variable('sort', 'get');//id DESC, modified DESC, created DESC,t.camp_start DESC,t.camp_end DESC
$param['id'] = pods_url_variable('id', 'get');
$param['type'] = pods_url_variable('type', 'get');//Offer Type dealcheck,quickcamp,daily,sale,exclusive,slider
$param['cities'] = pods_url_variable('cities', 'get');//mumbai,delhi,bengaluru.....
$param['category'] = pods_url_variable('category', 'get');//{category name} offers
$param['tags'] = pods_url_variable('tags', 'get');//{tag name} offers
$param['brands'] = pods_url_variable('brands', 'get');//{brand name}
$param['camp_start'] = pods_url_variable('from', 'get');
$param['camp_end'] = pods_url_variable('to', 'get');
$param['radius'] = pods_url_variable('radius', 'get');
if(!empty($param['radius'])){
  $map_items = $items;
  $items = -1;
}
$param['search'] = pods_url_variable('search', 'get');
$lat = pods_url_variable('lat', 'get');
$lng = pods_url_variable('lng', 'get');
$param['format'] = pods_url_variable('format', 'get');//rss, xml, json, total
$param['custom'] = pods_url_variable('t', 'get');
$page_no = pods_url_variable('page', 'get');
$apikey = pods_url_variable('apikey', 'get');

$api_pod = new Pod('api');
$api_pod->page = 1;
$api_pod->search = 1;
$api_pod->findRecords('id DESC', -1, "t.api_key ='$apikey'");
$api_exists = $api_pod->getTotalRows();
if($api_exists > 0)
{
	while($api_pod->fetchRecord()){
	  $client_name = $api_pod->get_field('name');
	  $client_name = explode('_',$client_name);
	  $client_name = $client_name[0];    
	}
}  

/* API Conditions Find Records Query String Begins */
foreach($param as $key => $value)
{
  if(!empty($value))
  {
    switch($key)
    {
      case 'id':
        $where .= 't.id='.$value." && ";
      break;
      
      /*
        Value can be any of these params or multiple params 
        (dealcheck,quickcamp,daily,sale,exclusive,slider)
        
        Example of link can be http://buzzr.in/rss/?type=dealcheck
        Another example http://buzzr.in/rss/?type=dealcheck,quickcamp
      */ 
      case 'type':
        $pos = strpos($value,',');
        if ($pos === false){
          $where .= $value."=1 && ";
        }
        else
        {
          $val = explode(',',$value);
          $count = count($val);
          for($i=0;$i<$count;$i++)
          {
            if($i == 0)
            {
              $where .= '(';
            }
            
            $where .= 't.'.$val[$i]."=1";
            if($i != ($count-1))
            {
              $where .= ' || ';
            }
            
            if($i == ($count-1))
            {
              $where .= ') && ';
            }
          }
        }
      break;
      
      case 'cities':
        $pos = strpos($value,',');
        if ($pos === false) {
          $city_name = $value;
          $where .= "city.name = '".$value."' && ";
        }
        else
        {
          $val = explode(',',$value);
          $count = count($val);
          for($i=0;$i<$count;$i++)
          { 
            $val_quote .= "'".$val[$i]."'";
            if($i != ($count-1))
            {
              $val_quote .= ',';
            }
          }
          $where .= "city.name IN(".$val_quote.") && "; 
        }
      break;
      
      case 'category':
        //echo $value;
        $pos = strpos($value,',');
        if ($pos === false) {
          $where .= "camp_cat.url = 'c-".sanitize_title($value)."-offers' && ";
        }
        else
        {
          $val = explode(',',$value);
          $count = count($val);
          for($i=0;$i<$count;$i++)
          { 
            $val_quote .= "'c-".sanitize_title($val[$i])."-offers'";
            if($i != ($count-1))
            {
              $val_quote .= ',';
            }
          }
          $where .= "camp_cat.url IN(".$val_quote.") && "; 
        }
      break;
      
      case 'tags':
        //echo $value;
        $pos = strpos($value,',');
        if ($pos === false) {
          
          $where .= "tag_pick.slug = 't-".sanitize_title($value)."' && ";
        }
        else
        {
          $val = explode(',',$value);
          $count = count($val);
          for($i=0;$i<$count;$i++)
          { 
            $val_quote .= "'t-".sanitize_title($val[$i])."'";
            if($i != ($count-1))
            {
              $val_quote .= ',';
            }
          }
          $where .= "tag_pick.slug IN(".$val_quote.") && "; 
        }
      break;
      
      case 'brands':
        //echo $value;
        $pos = strpos($value,',');
        if ($pos === false) {
          
          $where .= "brand.brandurl = '".sanitize_title($value)."' && ";
        }
        else
        {
          $val = explode(',',$value);
          $count = count($val);
          for($i=0;$i<$count;$i++)
          { 
            $val_quote .= "'".sanitize_title($val[$i])."'";
            if($i != ($count-1))
            {
              $val_quote .= ',';
            }
          }
          $where .= "brand.brandurl IN(".$val_quote.") && "; 
        }
      break;
      
       case 'radius':
          $where .= "Length(t.latlng) > 0 && ";
       break;
       
       case 'search':
          $where .= "(t.name LIKE '%$value%' OR t.short LIKE '%$value%') && ";
       break;
      
      case 'format':
        if($value == 'rss'){
           $rss = 1;
        }elseif($value == 'xml'){
          $xml = 1;
        }elseif($value == 'json'){
          $json = 1;
        }elseif($value == 'total'){
          $total = 1;
        }
        elseif($value == 'array'){
          $array = 1;
        }
      break;
      
      case 'custom':
         $pos = strpos($value,'-');
         if($pos === false)
         {
           if($value == 'localoffers')
           {
             $where .= "t.sale=1 && ";
             $name = 'deal';
           }
           elseif($value == 'dailydeals')
           {
             $where .= "t.daily=1 && ";
             $name = 'deal';
           }
         }
         else
         {
          $val = explode('-',$value);
          if($val['0'] == 'localoffers')
          {
            $where .= "t.sale=1 && city.name = '".ucwords($val['1'])."' && ";
            $name = 'deal';
          }
          elseif($val['0'] == 'dailydeals')
          {
            $where .= "t.daily=1 && city.name = '".ucwords($val['1'])."' && ";
            $name = 'deal';
          }
         }
      break; 
    }
  }
}

switch($name){
  case 'deal':
    $where .= 't.camp_end >= '.fix_date();
    break;
}


$pod_item = new Pod($name);

if(empty($page_no)){
$page_no = 1;
}
else{
$pod_item->page = $page_no;
}

if(!empty($items)){
  if(!empty($sort)){
    $pod_item->findRecords($sort, $items,$where);
  }
  else{
    $pod_item->findRecords('id DESC', $items,$where);      
  }
}
else
{
  if(!empty($sort)){
    $pod_item->findRecords($sort, 10,$where);
  }
  else{
    $pod_item->findRecords('id DESC', 10,$where);
  }
}

/* API Conditions Find Records Ends */

if($total == 1){
  echo $pod_item->getTotalRows();
}

if($xml == 1 || $json == 1 || $array == 1)
{
  $i = 0;
  while($pod_item->fetchRecord())
  {
    switch($name){
    case 'deal':
      
	  $extlink = $pod_item->get_field('extlink');
	  if(!empty($client_name)){
		$ut_string_app = '&utm_source=API&utm_medium=API&utm_campaign='.urlencode($client_name);
		$ut_string_pre = '?utm_source=API&utm_medium=API&utm_campaign='.urlencode($client_name);
	  }
	  
	  if(!empty($extlink)){
		  
		  $action = ucwords($pod_item->get_field('deal_provider.name'));
		  if(empty($action)){
			$action = ucwords($pod_item->get_field('brand.name'));
		  }
		  
		  $event = 'Online Deals~'.$action.'~'.$pod_item->get_field('name').'~'.$extlink;
		  $event = encrypt($event,'1b2u3z4z5r6');
		  $grab_deal = get_bloginfo('wpurl').'/wp-content/plugins/buzzr_tracking/redirect.php?p='.$event.$ut_string_app;
	  }
	  
      if(!empty($param['radius'])){
      
        $lat_lng = $pod_item->get_field('latlng');
        $latarr = explode(',',$lat_lng);  //latarr[0] has Latitude AND latarr[1] has Longitude
        $distance = (6371 * acos(cos(deg2rad((double)$lat)) * cos(deg2rad((double)$latarr[0])) * cos(deg2rad((double)$latarr[1]) - deg2rad((double)$lng)) + sin(deg2rad((double)$lat)) * sin(deg2rad((double)$latarr[0])))); //constant 6371 is for distance in km
       
        if(!empty($latarr[0]) && !empty($latarr[1])){
          if($distance <= $param['radius']){
            $deal_info[$i]['offer_id'] = $pod_item->get_field('id');
            $deal_info[$i]['offer_name'] = $pod_item->get_field('name');
            $deal_info[$i]['daily'] = $pod_item->get_field('daily');
            
	    $deal_info[$i]['offer_red_link'] = $grab_deal;
            $deal_info[$i]['offer_link'] = get_bloginfo('url').'/deals/'.$pod_item->get_field('camp_link').$ut_string_pre;

            $deal_info[$i]['offer_description'] = $pod_item->get_field('short');
            $deal_info[$i]['offer_terms'] = $pod_item->get_field('terms');
            
            $image = $pod_item->get_field('image');
            $thumbnail = wp_get_attachment_image_src($image[0][ID], 'thumbnail', false);
            $medium = wp_get_attachment_image_src($image[0][ID], 'medium', false);
            $full_image = wp_get_attachment_image_src($image[0][ID], 'full', false);
            $deal_info[$i]['offer_image_url'] = $thumbnail[0];
            $deal_info[$i]['offer_medium_image_url'] = $medium[0];
            $deal_info[$i]['offer_full_image_url'] = $full_image[0];
            
            $deal_info[$i]['offer_other_image'] = $pod_item->get_field('ext_image_url');
            $deal_info[$i]['offer_start_date'] = $pod_item->get_field('camp_start');
            $deal_info[$i]['offer_end_date'] = $pod_item->get_field('camp_end');
            $deal_info[$i]['offer_location'] = $pod_item->get_field('location');
            if(empty($deal_info[$i]['offer_location'])){
                $deal_info[$i]['offer_location'] = $pod_item->get_field('deal_address');
            }
            $deal_info[$i]['offer_cities'] = $pod_item->get_field('city.name');
            $deal_info[$i]['offer_categories'] = $pod_item->get_field('camp_cat.name');
            $deal_info[$i]['offer_categories_url'] = get_bloginfo('url').'/c-'.sanitize_title($deal_info[$i]['offer_categories']).'-offers'.$ut_string_pre;
            $deal_info[$i]['offer_brand'] = $pod_item->get_field('brand.name');
            $deal_info[$i]['offer_brand_url'] = get_bloginfo('url').'/brands/'.$pod_item->get_field('brand.brandurl').$ut_string_pre;
            $deal_info[$i]['offer_deal_provider'] = $pod_item->get_field('deal_provider.name');
            $deal_info[$i]['offer_deal_provider_url'] = get_bloginfo('url').'/brands/'.$pod_item->get_field('deal_provider.brandurl').$ut_string_pre;
            $deal_info[$i]['offer_brand_image'] = $pod_item->get_field('brand.logo.guid');
            $deal_info[$i]['online'] = $pod_item->get_field('quickcamp');
            $deal_info[$i]['localoffer'] = $pod_item->get_field('sale');
            $deal_info[$i]['coupon'] = $pod_item->get_field('coupon');
            $deal_info[$i]['coupon_code'] = $pod_item->get_field('couponcode');
            $deal_info[$i]['exclusive'] = $pod_item->get_field('exclusive');
            $deal_info[$i]['latlng'] = $pod_item->get_field('latlng');
          }
        }
      }
      else{
        $deal_info[$i]['offer_id'] = $pod_item->get_field('id');
        $deal_info[$i]['offer_name'] = $pod_item->get_field('name');
        $deal_info[$i]['daily'] = $pod_item->get_field('daily');
		
		$deal_info[$i]['offer_red_link'] = $grab_deal;
        $deal_info[$i]['offer_link'] = get_bloginfo('url').'/deals/'.$pod_item->get_field('camp_link').$ut_string_pre;
        
        $deal_info[$i]['offer_description'] = $pod_item->get_field('short');
        $deal_info[$i]['offer_terms'] = $pod_item->get_field('terms');
        
        $image = $pod_item->get_field('image');
        $thumbnail = wp_get_attachment_image_src($image[0][ID], 'thumbnail', false);
        $medium = wp_get_attachment_image_src($image[0][ID], 'medium', false);
        $full_image = wp_get_attachment_image_src($image[0][ID], 'full', false);
        $deal_info[$i]['offer_image_url'] = $thumbnail[0];
        $deal_info[$i]['offer_medium_image_url'] = $medium[0];
        $deal_info[$i]['offer_full_image_url'] = $full_image[0];
        
        $deal_info[$i]['offer_other_image'] = $pod_item->get_field('ext_image_url');
        $deal_info[$i]['offer_start_date'] = $pod_item->get_field('camp_start');
        $deal_info[$i]['offer_end_date'] = $pod_item->get_field('camp_end');
        $deal_info[$i]['offer_location'] = $pod_item->get_field('location');
        if(empty($deal_info[$i]['offer_location'])){
            $deal_info[$i]['offer_location'] = $pod_item->get_field('deal_address');
        }
        $deal_info[$i]['offer_cities'] = $pod_item->get_field('city.name');
        $deal_info[$i]['offer_categories'] = $pod_item->get_field('camp_cat.name');
        $deal_info[$i]['offer_categories_url'] = get_bloginfo('url').'/c-'.sanitize_title($deal_info[$i]['offer_categories']).'-offers'.$ut_string_pre;
        $deal_info[$i]['offer_brand'] = $pod_item->get_field('brand.name');
        $deal_info[$i]['offer_brand_url'] = get_bloginfo('url').'/brands/'.$pod_item->get_field('brand.brandurl').$ut_string_pre;
        $deal_info[$i]['offer_deal_provider'] = $pod_item->get_field('deal_provider.name');
        $deal_info[$i]['offer_deal_provider_url'] = get_bloginfo('url').'/brands/'.$pod_item->get_field('deal_provider.brandurl').$ut_string_pre;
        $deal_info[$i]['offer_brand_image'] = $pod_item->get_field('brand.logo.guid');
        $deal_info[$i]['online'] = $pod_item->get_field('quickcamp');
        $deal_info[$i]['localoffer'] = $pod_item->get_field('sale');
        $deal_info[$i]['coupon'] = $pod_item->get_field('coupon');
        $deal_info[$i]['coupon_code'] = $pod_item->get_field('couponcode');
        $deal_info[$i]['exclusive'] = $pod_item->get_field('exclusive');
        $deal_info[$i]['latlng'] = $pod_item->get_field('latlng');
      }
    break;
    
    case 'category':
      $deal_info[$i]['name'] = $pod_item->get_field('name');
      $deal_info[$i]['slug'] = sanitize_title($deal_info[$i]['name']);
      $deal_info[$i]['is_local'] = $pod_item->get_field('is_local');
      $deal_info[$i]['is_daily'] = $pod_item->get_field('is_daily');
      $deal_info[$i]['image'] = $pod_item->get_field('image.guid');
    break;
    }
      $i++;
  }
 
  if($xml == 1)
  {
    //echo array2xml($deal_info);
    $xml = new arr2xml($deal_info);
    header ("content-type: text/xml");
    echo $xml->get_xml(); 
  }
  elseif($json == 1)
  {
    if(!empty($param['radius'])){
      $deal_info = array_slice($deal_info, 0, $map_items);
    }
    echo json_encode($deal_info);
  }
  elseif($array == 1){ 
    echo "<pre>";
    print_r($deal_info);
    exit();
  }   
}


//If RSS format then print feed
if($rss == '1')
{
    include("/home/kunal17/public_html/buzzr/wordpress/wp-content/plugins/buzzr_feedcreator/include/feedcreator.class.php");
    $rss = new UniversalFeedCreator();
    if(!empty($city_name))
    {
        date_default_timezone_set('Asia/Kolkata');
        $rss->title = 'Best '.ucwords($city_name).' Deals for '.date('M d,Y');
    }
    else
    {
        $rss->title = 'Best Deals from Buzzr.in';
    }
    $rss->description = 'Buzzr.in helps you save money on quality brands and products. We collect the best deals, offers, and promo codes from brands and stores you shop at every day and make it easy for you to discover and share these offers with your friends.';
    $rss->link="http://buzzr.in/";
    $rss->syndicationURL="http://buzzr.in/$PHP_SELF";
    
    while($pod_item->fetchRecord())
    {
		$item = new FeedItem();
		$item->title = $pod_item->get_field('name');
      
		$link = get_bloginfo('url').'/deals/'.$pod_item->get_field('camp_link');
		$item->link =  $link;
		
		$image_link = $pod_item->get_field('image.guid');
		if(empty($image_link))
		{
		  $image_link = $pod_item->get_field('ext_image_url');
		}
		
		$item->description = '<a href="'.$link.'"><img width="10%" height="15%" src="'.$image_link.'" /></a><br />'.$pod_item->get_field('short');
      
		$item->date = strtotime($pod_item->get_field('camp_start'));
       
		$rss->addItem($item);
    }
    $rss->outputFeed("RSS2.0");
    exit;
}
//If RSS format then print feed
?>